﻿Imports System.Runtime.CompilerServices

Public Module IDbConnectionExtension

    ''' <summary>
    ''' Loaderに変換します
    ''' </summary>
    ''' <param name="source"></param>
    ''' <param name="prefix"></param>
    ''' <returns></returns>
    ''' <remarks>#119 IDbConnectionの拡張メソッドでLoad</remarks>
    <Extension()>
    Public Function ToLoader(source As IDbConnection, prefix As String) As Loader
        Return New Loader(source, prefix)
    End Function

    ''' <summary>
    ''' DB接続します
    ''' </summary>
    ''' <param name="source"></param>
    ''' <param name="prefix"></param>
    ''' <param name="core"></param>
    ''' <remarks>#124 DB接続処理を簡便に</remarks>
    <Extension>
    Public Sub Connect(source As IDbConnection, prefix As String, core As Action(Of Loader))
        If source Is Nothing Then Throw New ArgumentNullException("source")
        If core Is Nothing Then Throw New ArgumentNullException("core")

        Try
            source.Open()
            Dim r = source.ToLoader(prefix)
            core.Invoke(r)
        Finally
            source.Dispose()
        End Try
    End Sub

    ''' <summary>
    ''' DB接続しトランザクション処理を行います
    ''' </summary>
    ''' <param name="source"></param>
    ''' <param name="prefix"></param>
    ''' <param name="core"></param>
    ''' <remarks>#124 DB接続処理を簡便に</remarks>
    <Extension>
    Public Sub Transact(source As IDbConnection, prefix As String, core As Action(Of Saver))
        If source Is Nothing Then Throw New ArgumentNullException("source")
        If core Is Nothing Then Throw New ArgumentNullException("core")

        Try
            source.Open()
            Using trn = source.BeginTransaction
                Try
                    Dim r = Saver.Create(trn, prefix)
                    core.Invoke(r)
                    trn.Commit()
                Catch ex As Exception
                    trn.Rollback()
                    Throw
                End Try
            End Using
        Finally
            source.Dispose()
        End Try
    End Sub
End Module
